//
//  LoadViewController.m
//  STL_ Animation
//
//  Created by 孙健 on 16/3/30.
//  Copyright © 2016年 STL. All rights reserved.
//

#import "LoadViewController.h"
#import "AppDelegate.h"
#include <sys/param.h>
#include <sys/mount.h>
#import "MusicYue_V_TableViewCell.h"
#import "LoadTwoTableViewCell.h"
#import "MusicYue_V_ViewController.h"
#import "MusicYue_V_Model.h"
#import "CoreDataManager.h"
#import "MvLoad.h"
#import "STLLoadMv.h"
#import "STLoadModel.h"
@interface LoadViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) UIView *OneView;
@property (nonatomic, strong) UIView *TwoView;
@property (nonatomic, strong) UITableView *tableViewOne;
@property (nonatomic, strong) UITableView *tableViewTwo;
@property (nonatomic, strong) NSMutableArray *dataSourceOne;
@property (nonatomic, strong) NSMutableArray *dataSourceTwo;
@property (nonatomic, strong) NSMutableArray *loadSource;

@property (nonatomic, strong) MusicYue_V_ViewController *musicVc;
@property (nonatomic, strong) CoreDataManager *coreDataManeger;
//@property (nonatomic, strong) LoadTwoTableViewCell *cell;

#pragma mark ------下载
@property (nonatomic, strong) NSData *dataLoad;
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSString *filepath;
@property (nonatomic, strong) NSString *string;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, assign) NSInteger count;

@end

@implementation LoadViewController

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    NSLog(@"%lld GB", freeSpace());
    NSLog(@"%.2f GB", [[self class] getTotalDiskSpaceInBytes]);
    
   
    [self spaceView];
}



- (void)viewDidLoad {
    
    self.coreDataManeger = [CoreDataManager shareCoreDataManager];
    [super viewDidLoad];
    self.dataSourceOne = [NSMutableArray arrayWithCapacity:0];
    self.dataSourceTwo = [NSMutableArray arrayWithCapacity:0];
    self.loadSource = [NSMutableArray arrayWithCapacity:0];
    self.musicVc = [[MusicYue_V_ViewController alloc] init];
    self.view.backgroundColor = [UIColor blackColor];
    self.navigationItem.title = @"下载列表";
    [self selectData];
    [self createSegment];
    [self createTwoView];
    [self createOneView];
     NSLog(@"%@", NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES));
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 从coredata中查询并且拿出数据
- (void)selectData {
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MvLoad" inManagedObjectContext:self.coreDataManeger.managedObjectContext];
    [request setEntity:entity];
    
    NSError *error = nil;
    NSArray *array = [self.coreDataManeger.managedObjectContext executeFetchRequest:request error:&error];
    if (array == nil) {
        
        NSLog(@"%@", error);
    }else {
        
        for (MvLoad *load in array) {
            
            LoadViewModel *loadModel = [[LoadViewModel alloc] init];
            loadModel.loadUrl = load.url;
            loadModel.titleName = load.title;
            loadModel.imageViewTitle = load.picture;
            [self.dataSourceTwo addObject:loadModel];
        }
        
        NSLog(@"^^^%@^^^^", self.dataSourceTwo);
        if (self.dataSourceTwo) {
         
        for (LoadViewModel *model in self.dataSourceTwo) {
                NSLog(@"%@", model.titleName);
                [self.loadSource addObject:model.loadUrl];
            }
            
        NSLog(@"%@", self.loadSource);
        }
        
    }
}


#pragma mark - 创建segment
- (void)createSegment {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, [UIScreen mainScreen].bounds.size.height * 0.045)];
    view.backgroundColor = [UIColor blackColor];
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"已下载",@"正在下载"]];
    self.segment.frame = CGRectMake(10, 0, self.view.bounds.size.width - 20, view.bounds.size.height - 1);
    
    self.segment.backgroundColor = [UIColor blackColor];
    self.segment.tintColor = [UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1];
    [self.segment setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
    [self.segment.layer setCornerRadius:CGRectGetHeight([self.segment bounds])/4];
    self.segment.layer.masksToBounds = YES;
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    self.segment.selectedSegmentIndex = 0;
    
    [view addSubview:self.segment];
    [self.view addSubview:view];
}

#pragma mark - segment的点击事件
- (void)segmentAction:(id)sender {
    
    NSInteger selectIndex = self.segment.selectedSegmentIndex;
    if (selectIndex == 0) {
        
        [self.view sendSubviewToBack:self.TwoView];
        [self.view bringSubviewToFront:self.OneView];
        
        
    }else if (selectIndex == 1) {
        [self checkNetworking];
        [self.view bringSubviewToFront:self.TwoView];
        [self.view sendSubviewToBack:self.OneView];
        
    }
    
}

#pragma mark - 创建显示手机内存的view
- (void)spaceView{
    
    UIView *viewSpace = [[UIView alloc] initWithFrame:CGRectMake(0, self.TwoView.bounds.size.height - 64, self.TwoView.bounds.size.width, 64)];
    viewSpace.backgroundColor = [UIColor blackColor];
    UILabel *label = [[UILabel alloc] initWithFrame:viewSpace.bounds];
    
    UIButton *buttonStrat = [UIButton buttonWithType:UIButtonTypeSystem];
    buttonStrat.frame = CGRectMake(0, 0, self.TwoView.bounds.size.width/2, 40);
    
    
    NSString *stringMove = @"首MV共";
    NSString *stringChinese = @"(剩余可用空间";
    NSString *stringStl = @"G)";
    NSString *stringCountmove = [NSString stringWithFormat:@"%ld",self.dataSourceTwo.count];
    NSString *stringfreeSpace = [NSString stringWithFormat:@"%lld",freeSpace()];
    NSString *stringMv = [self freeSpaceFile];
    NSString *string = [NSString stringWithFormat:@"%ld首MV共%@(剩余可用空间%lldG)",self.loadSource.count,[self freeSpaceFile],freeSpace()];
    
    NSRange rangeMove = [string rangeOfString:stringMove];
    NSRange rangeChinese = [string rangeOfString:stringChinese];
    NSRange rangeStl = [string rangeOfString:stringStl];
    NSRange rangeCountmove = [string rangeOfString:stringCountmove];
    NSRange rangefreeSpace = [string rangeOfString:stringfreeSpace];
    NSRange rangeMv = [string rangeOfString:stringMv];

    NSMutableAttributedString *stringEndmove = [[NSMutableAttributedString alloc] initWithString:string];
    [stringEndmove addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:rangeMove];
    [stringEndmove addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:rangeChinese];
    [stringEndmove addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:rangeStl];
    [stringEndmove addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1] range:rangeCountmove];
    [stringEndmove addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1] range:rangefreeSpace];
    [stringEndmove addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1] range:rangeMv];
    label.attributedText = stringEndmove;
    label.font = [UIFont systemFontOfSize:12];
    label.textAlignment = NSTextAlignmentCenter;
    
    [viewSpace addSubview:label];
    [self.TwoView addSubview:viewSpace];
}


#pragma mark - 正在下载的view界面
- (void)createTwoView {
    
    self.TwoView = [[UIView alloc] initWithFrame:CGRectMake(0, self.segment.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height - self.segment.bounds.size.height - 64)];
    self.TwoView.backgroundColor = [UIColor greenColor];
    if (self.dataSourceTwo.count == 0) {
        UIImageView *imageViewtwo = [[UIImageView alloc] initWithFrame:self.TwoView.bounds];
        imageViewtwo.image = [[UIImage imageNamed:@"55555"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.TwoView addSubview:imageViewtwo];
        [self.view addSubview:self.TwoView];
    } else {
        
        self.tableViewTwo = [[UITableView alloc] initWithFrame:self.TwoView.bounds style:UITableViewStylePlain];
        self.tableViewTwo.dataSource = self;
        self.tableViewTwo.delegate = self;
        
        [self.tableViewTwo registerClass:[LoadTwoTableViewCell class] forCellReuseIdentifier:@"LoadTwoTableViewCell"];
        [self.TwoView addSubview:self.tableViewTwo];
        [self.view addSubview:self.TwoView];
        }
}
#pragma mark -  已经下载完成的view界面
- (void)createOneView {
    
    self.OneView = [[UIView alloc] initWithFrame:CGRectMake(0, self.segment.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height - self.segment.bounds.size.height - 64)];
    
    self.OneView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.OneView];
    
    self.tableViewOne = [[UITableView alloc] initWithFrame:self.OneView.bounds style:UITableViewStylePlain];
    self.tableViewOne.dataSource = self;
    self.tableViewOne.delegate = self;
    
    [self.tableViewOne registerClass:[MusicYue_V_TableViewCell class] forCellReuseIdentifier:@"MusicYue_V_TableViewCell"];
    
    [self.OneView addSubview:self.tableViewOne];
}

#pragma mark - tableview的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.tableViewOne) {
        return self.dataSourceOne.count;
    }else {
        
        return self.dataSourceTwo.count;
    }
    
}

#pragma mark - tableview的协议方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.tableViewOne) {
        
        MusicYue_V_TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MusicYue_V_TableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    else {
        
        LoadTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LoadTwoTableViewCell"];
        
        NSURLSessionDownloadTask *task = [[STLLoadMv sharedInstance] getTask:self.loadSource[indexPath.row]];
        
        STLoadModel *model = [[STLLoadMv sharedInstance] getSessionModel:task.taskIdentifier];
        model.progressBlock = ^(CGFloat progress){
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSLog(@"下载进度为%f", progress);
                NSString *string = [NSString stringWithFormat:@"%.2f%%", progress];
                cell.labelCount.text = string;
                cell.progressView.progress = progress / 100;
                if (cell.progressView.progress == 1) {
                    
                    [self deleteActivity:indexPath.row];
                }
            });

        };
        
        cell.block = ^(NSInteger count) {
            
            [[STLLoadMv sharedInstance] download:self.loadSource[indexPath.row] progress:^(CGFloat progress) {
                
            } state:^(DownloadState state) {
                
            }];
        };
        cell.count = indexPath.row;
        cell.dataSourceUrl = self.loadSource;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.buttonLoad addTarget:self action:@selector(buttonLoad) forControlEvents:UIControlEventTouchUpInside];
        cell.loadModel = self.dataSourceTwo[indexPath.row];
        cell.tag = 1001;
        return cell;
    }
    
}

#pragma mark --------------按键点击事件
- (void)buttonLoad {
    
    
 
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return (self.view.bounds.size.width - ([UIScreen mainScreen].bounds.size.height * 0.045) - 64)/3;
}


#pragma mark - 计算当前磁盘空间
long long freeSpace() {
    
    struct statfs buf;
    long long freespace = -1;
    if(statfs("/", &buf) >= 0){
        
        freespace = (long long)buf.f_bsize * buf.f_bfree;
    }
    
    
    return freespace/1024/1024/1024;
}

#pragma mark - 计算当前剩余磁盘空间
+(float)getTotalDiskSpaceInBytes {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    struct statfs tStats;
    statfs([[paths lastObject] cString], &tStats);
    float totalSpace = (float)(tStats.f_blocks * tStats.f_bsize);
    return totalSpace/1024/1024/1024;
}

#pragma mark - 计算文件夹里所有文件的大小
- (NSString *)freeSpaceFile {
    
        NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
        NSFileManager *manage = [NSFileManager defaultManager];
        if (![manage fileExistsAtPath:path]) {
            return 0;
        }
        NSEnumerator *enumerator = [[manage subpathsAtPath:path] objectEnumerator];
        NSString *fileName = [NSString string];
        float fileSize = 0;
        while ((fileName = [enumerator nextObject]) != nil) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            fileSize += [self fileSizeAtPath:absolutePath];
        }
        return [NSString stringWithFormat:@"%.2fM", fileSize / (1024.0 * 1024.0)];
}


#pragma mark - 计算单个文件的大小
- (long long)fileSizeAtPath:(NSString *)path
{
    NSFileManager *manage = [NSFileManager defaultManager];
    if ([manage fileExistsAtPath:path]) {
        return [[manage attributesOfItemAtPath:path error:nil]fileSize];
    }
    return 0;
}

#pragma mark - ----------创建检测网络状态
- (void)checkNetworking {
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
       
        if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
            
            NSLog(@"当前网络为wife");
        }
        if (status == AFNetworkReachabilityStatusReachableViaWWAN) {
            
            NSLog(@"当前网络为3g");
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"当前为3G网络 是否要下载" preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self.view sendSubviewToBack:self.TwoView];
                [self.view bringSubviewToFront:self.OneView];
                self.segment.selectedSegmentIndex = 0;

                
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                
            }]];
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];

        }
        
        if (status == AFNetworkReachabilityStatusNotReachable) {
            
            NSLog(@"当前没有网络");
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"当前没有网络 无法下载" preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self.view sendSubviewToBack:self.TwoView];
                [self.view bringSubviewToFront:self.OneView];
                self.segment.selectedSegmentIndex = 0;
            }]];
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];

        }
        
        if (status == AFNetworkReachabilityStatusUnknown) {
            
            NSLog(@"当前为未知网络");
        }
    }];
}






#pragma mark ----------- tableview的动态删除
- (void)deleteActivity:(NSInteger)count {
//    应该回到主线程 因为下载是在子线程完成的，如果不回到主线程对tableviewcell的操作是无效的。
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSLog(@"%ld", count);
        [self.tableViewTwo beginUpdates];
        [self.dataSourceTwo removeObjectAtIndex:count];
        NSArray *array = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:count inSection:0]];
        NSLog(@"======%d",[NSThread isMainThread]);
        [self.tableViewTwo deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationFade];
        [self.tableViewTwo endUpdates];
    });
    
}

- (void)deleteCoredata:(NSInteger)count {
    
    for (MvLoad *load in self.dataSourceTwo) {
        
        if ([load.url isEqualToString:self.loadSource[count]]) {
            
            [self.coreDataManeger.managedObjectContext deleteObject:load];
        }
    }
    
    [self.coreDataManeger saveContext];
}

@end
